package com.hengpeng.itfinoss.controller.acm;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hengpeng.common.acl.vo.Passport.Token;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Restrictions;
import com.hengpeng.common.util.MD5;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.AppGroup;
import com.hengpeng.itfinbase.persist.AppRole;
import com.hengpeng.itfinbase.persist.AppUser;
import com.hengpeng.itfinbase.persist.AppUser.UserStatus;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.CollectionHelp;

/**
 * <pre>
 * 操作员管理控制层
 * </pre>
 * @author CHARLES
 * @version 1.0, 2010-8-10
 */
@Controller
@RequestMapping("/acm/appuser")
public class AppUserController  extends BaseController
{
	@Autowired(required = false)
	protected ServiceFactory serviceFactory;

	@RequestMapping(value = "/list")
	public String list(ModelMap map, HttpServletRequest request)
	{
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			DynamicQuery query = new DynamicQuery(AppUser.class);
			query.setIsSearchTotalCount(true);
			query.setPageIndex(page.currentPage);
			query.setPageSize(page.pageSize);
			query.asc("userNo");
			QueryResult<AppUser> result = serviceFactory.getPersistService().findWithPage(AppUser.class, query);
			page.setEntityCount((int) result.getTotalCount());
			map.put("list", result.getResults());
			map.put("page", page);
			return "acm/appUserList";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/load/{id}")
	public String load(@PathVariable Long id, ModelMap map)
	{
		if (PageHandlerUtil.validateObjectsNullOrEmpty(id))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		// 当前用户已经存在的角色
		Set<AppRole> roleSet = null;
		// 当前用户已经存在的组
		Set<AppGroup> groupSet = null;
		try
		{
			AppUser appuser = serviceFactory.getPersistService().get(AppUser.class, id);
			if (appuser == null)
			{
				return PageHandlerUtil.returnError(map, "该操作员不存在");
			}
			roleSet = appuser.getRoles();
			groupSet = appuser.getGroups();
			map.put("appuser", appuser);
			map.put("rolelist", roleSet);
			map.put("grouplist", groupSet);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
		List<AppRole> roleListAll = serviceFactory.getPersistService().list(AppRole.class);
		List<AppGroup> groupListAll = serviceFactory.getPersistService().list(AppGroup.class);
		// 角色及系统组差异值集合
		Collection<AppRole> roleListDiff = CollectionHelp.findCollectionDiff(roleListAll, roleSet);
		Collection<AppGroup> groupListDiff = CollectionHelp.findCollectionDiff(groupListAll, groupSet);
		map.put("rolelistdiff", roleListDiff);
		map.put("grouplistdiff", groupListDiff);
		return "acm/appUserModify";
	}

	@RequestMapping(value = "/create")
	public String initSave(ModelMap map)
	{
		List<AppRole> roleList = serviceFactory.getPersistService().list(AppRole.class);
		List<AppGroup> groupList = serviceFactory.getPersistService().list(AppGroup.class);
		map.put("appuser", new AppUser());
		map.put("rolelist", roleList);
		map.put("grouplist", groupList);
		return "acm/appUserCreate";
	}

	@RequestMapping(value = "/onsave")
	public String save(String userNo, String loginName, String nickName, String password, String realName,
			String phone, String email, String state, String token, Long[] groups, Long[] roles,
			ModelMap map, HttpSession session)
	{
		if (PageHandlerUtil.validateObjectsNullOrEmpty(userNo, loginName, nickName, password, realName, phone, email,
				state))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		Set<AppRole> roleSet = null;
		Set<AppGroup> groupSet = null;
		// 判断前台传入的角色ID数组和系统组ID数组是否存在
		if (roles != null && roles.length > 0)
		{
			DynamicQuery query = new DynamicQuery(AppRole.class);
			query.add(Restrictions.inArray("id", roles));
			List<AppRole> roleList = serviceFactory.getPersistService().find(AppRole.class, query);
			if (roleList == null || roleList.size() <= 0 || roleList.size() != roles.length)
			{
				return PageHandlerUtil.returnError(map, "您选中的角色已经不存在，请刷新页面后重试！");
			}
			roleSet = new HashSet<AppRole>(roleList);
		}

		if (groups != null && groups.length > 0)
		{
			DynamicQuery queryGroup = new DynamicQuery(AppGroup.class);
			queryGroup.add(Restrictions.inArray("id", groups));
			List<AppGroup> groupList = serviceFactory.getPersistService().find(AppGroup.class, queryGroup);
			if (groupList == null || groupList.size() <= 0 || groupList.size() != groups.length)
			{
				return PageHandlerUtil.returnError(map, "您选中的系统组已经不存在，请刷新页面后重试！");
			}
			groupSet = new HashSet<AppGroup>(groupList);
		}

		List<AppUser> __list = serviceFactory.getAppUserService().findUsers(null, userNo, null, null,
				Constant.G_INT_DATA_INVALID, Constant.G_INT_DATA_INVALID, null, null);
		if (__list.size() > 0)
		{
			return PageHandlerUtil.returnError(map, "用户编号已经存在!");
		}
		__list = serviceFactory.getAppUserService().findUsers(loginName, null, null, null, Constant.G_INT_DATA_INVALID,
				Constant.G_INT_DATA_INVALID, null, null);
		if (__list.size() > 0)
		{
			return PageHandlerUtil.returnError(map, "登录名已经存在!");
		}

	

		UserStatus userStatus = null;
		Token userToken = null;
		if (token != null)
		{
			userToken = Token.valueOf(token);
		}
		if (state != null)
		{
			userStatus = UserStatus.valueOf(state);
		}
		try
		{
			// 校验数据无误，进入持久化操作
			serviceFactory.getAppUserService().save(userNo, loginName, nickName, MD5.encodeString(password, "utf-8"),
					realName, phone, email, userStatus, userToken, groupSet, roleSet);
			return PageHandlerUtil.returnSuccess(map, "/acm/appuser/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/onmodify")
	public String modify(Long id, String userNo, String loginName, String nickName, String password, String realName,
			String phone, String email, String state, String token, Long[] groups, Long[] roles,
			ModelMap map, HttpSession session)
	{
		if (PageHandlerUtil.validateObjectsNullOrEmpty(id, userNo, loginName, nickName, password, realName, phone,
				email, state))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		// 判断是否修改了密码
		AppUser beforeUser = serviceFactory.getPersistService().get(AppUser.class, id);
		if (beforeUser.getPassword().equals(password))
		{
			password = null;
		}
		else
		{
			password = MD5.encodeString(password, "utf-8");
		}
		Set<AppRole> roleSet = new HashSet<AppRole>();
		Set<AppGroup> groupSet = new HashSet<AppGroup>();

		// 判断前台传入的角色ID数组和系统组ID数组是否存在
		if (roles != null && roles.length > 0)
		{
			List<AppRole> roleList = serviceFactory.getAppUserService().findUserRoleByIds(roles);
			if (roleList == null || roleList.size() <= 0 || roleList.size() != roles.length)
			{
				return PageHandlerUtil.returnError(map, "您选中的角色已经不存在，请刷新页面后重试！");
			}
			roleSet = new HashSet<AppRole>(roleList);
		}
		if (groups != null && groups.length > 0)
		{
			List<AppGroup> groupList = serviceFactory.getAppUserService().findGroupByIds(groups);
			if (groupList == null || groupList.size() <= 0 || groupList.size() != groups.length)
			{
				return PageHandlerUtil.returnError(map, "您选中的系统组已经不存在，请刷新页面后重试！");
			}
			groupSet = new HashSet<AppGroup>(groupList);
		}

		

		AppUser user = new AppUser();
		user.setId(id);

		List<AppUser> __list = serviceFactory.getAppUserService().findUsers(null, userNo, null, null,
				Constant.G_INT_DATA_INVALID, Constant.G_INT_DATA_INVALID, null, null);
		if (__list.size() > 1 || (__list.size() > 0 && !__list.get(0).getId().equals(id)))
		{
			return PageHandlerUtil.returnError(map, "用户编号已经存在!");
		}
		__list = serviceFactory.getAppUserService().findUsers(loginName, null, null, null, Constant.G_INT_DATA_INVALID,
				Constant.G_INT_DATA_INVALID, null, null);
		if (__list.size() > 1 || (__list.size() > 0 && !__list.get(0).getId().equals(id)))
		{
			return PageHandlerUtil.returnError(map, "用户编号已经存在!");
		}

		UserStatus userStatus = null;
		Token userToken = null;
		if (token != null)
		{
			userToken = Token.valueOf(token);
		}
		if (state != null)
		{
			userStatus = UserStatus.valueOf(state);
		}
		try
		{
			serviceFactory.getAppUserService().modify(id, userNo, loginName, nickName, password, realName, phone,
					email, userStatus, userToken, null, groupSet, roleSet);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
		return PageHandlerUtil.returnSuccess(map, "/acm/appuser/list");
	}

	@RequestMapping(value = "/del")
	public String remove(Long[] ids, HttpSession session, ModelMap map)
	{
		if (PageHandlerUtil.validateArrayNullOrEmpty(ids))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		List<AppUser> userList = serviceFactory.getAppUserService().findUserByIds(ids);
		for (AppUser user : userList)
		{
			if (user.getLoginName().toLowerCase().equals("admin"))
			{
				return PageHandlerUtil.returnError(map, "不能删除admin用户！");
			}
		}
		try
		{
			Set<Object> set = new HashSet<Object>(Arrays.asList(ids));
			serviceFactory.getAppUserService().delete(PageHandlerUtil.getUserNo(session), set);
			return PageHandlerUtil.returnSuccess(map, "/acm/appuser/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

}
